package com.antdesignbackend.backend.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.config.WxMaConfiguration;
import com.antdesignbackend.backend.entity.UserRoles;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.AppletUserRoleVo;
import com.antdesignbackend.backend.service.UserRolesService;
import com.antdesignbackend.backend.service.UserService;
import com.antdesignbackend.backend.util.JsonUtils;
import com.antdesignbackend.backend.util.WXCore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.chanjar.weixin.common.error.WxErrorException;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/user")
public class WxMaUserController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserRolesService userRolesService;

    @Autowired
    UserService userService;

    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public ReturnVO login(@RequestParam(required = false) String code,
                          @RequestParam(required = false) String nickName,
                          @RequestParam(required = false) String avatarUrl,
                          @RequestParam(required = false) Integer gender,
                          @RequestParam(required = false) String city,
                          @RequestParam(required = false) String province,
                          @RequestParam(required = false) String country,
                          @RequestParam(required = false) String language,
                          @RequestParam(required = false) String promotionCode,
                          @RequestParam(required = false) String iv,
                          @RequestParam(required = false) String encryptedData,
                          HttpServletRequest request) {

        logger.info("----------------code"+code);
        logger.info("-----------------------我是登录接口");
        logger.info("-----------------------我是推广码"+promotionCode);
        ReturnVO returnVO = new ReturnVO();
        if (StringUtils.isBlank(code)) {
            returnVO.setCode("500");
            returnVO.setMessage("empty jscode");
            return returnVO;
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(WebConfig.APPID);

        try {

            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            //TODO 可以增加自己的逻辑，关联业务相关数据
            logger.error("微信获取openid："+JsonUtils.toJson(session));

            String openid = session.getOpenid();
            if (openid == null || openid.equals("")){
                if (request.getSession().getAttribute("openid") != null){
                    openid = request.getSession().getAttribute("openid").toString();
                }
            }

            Integer memberId = null;
            Integer parentID = 1;
            if (promotionCode != null && !promotionCode.equals("")){ //通过会员推广码，找到推广的用户id 推广码存在的情况
                QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("promotionCode",promotionCode)
                            .notIn("openid",openid); //排除自己
                Users users = userService.getOne(queryWrapper); // null
                if(users != null){
                    if(users.getUserType().equals(2)){
                        memberId = null;
                        parentID = users.getUserID();
                    }else if(users.getUserType().equals(5)){
                        memberId = users.getUserID();
                        parentID = users.getParentID();
                    }
                    logger.info("推广的用户==============="+memberId+parentID);
                    //用户角色是 会员和合伙人的角色做处理
                    QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
                    usersQueryWrapper.eq("openid",openid); //找到自己
                    Users users1 = userService.getOne(usersQueryWrapper);
                    if (users1 != null){
                        //角色的用户
                        if (users1.getUserType() == 5 && users1.getUserType() == 2){
                            memberId = users1.getMemberId();
                            parentID = users1.getParentID();
                        }
                    }
                }else{
                    //自己扫自己
                    QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
                    usersQueryWrapper.eq("openid",openid); //找到自己
                    Users users2 = userService.getOne(usersQueryWrapper);
                    if (users2 != null){
                        memberId = users2.getMemberId();
                        parentID = users2.getParentID();
                    }
                }
            }else {
                QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
                usersQueryWrapper.eq("openid",openid); //找到自己
                Users users = userService.getOne(usersQueryWrapper);
                if (users != null){ //用户存在
                    memberId = users.getMemberId();
                    parentID = users.getParentID();
                }
            }

            if (openid != null && !openid.equals("")){
                try {
                    //根据openid查询该用户存不存在 如果存在 返回推广码、会员推广码、userId；如果不存在，创建该用户，生成推广码，会员推广码
                    QueryWrapper<AppletUserRoleVo> usersQueryWrapper = new QueryWrapper<>();
                    usersQueryWrapper.eq("OpenId",openid);
                    AppletUserRoleVo appletUserRoleVo = userRolesService.getAppletUserRoleVo(usersQueryWrapper);
                    //解密获取手机号
                    String phone="";
                    logger.info("-----------------------encryptedData:"+encryptedData);
                    logger.info("-----------------------SessionKey:"+session.getSessionKey());
                    logger.info("-----------------------iv:"+iv);
                    if(encryptedData!=null && iv!=null && !encryptedData.equals("") && !iv.equals("")){
                        WxMaPhoneNumberInfo phoneNoInfo=wxService.getUserService().getPhoneNoInfo(session.getSessionKey(),encryptedData,iv);
                        logger.info("-----------------------phoneNoInfo:"+phoneNoInfo);
                        if(phoneNoInfo.getPhoneNumber()!=null && !phoneNoInfo.getPhoneNumber().equals("")){
                            phone=phoneNoInfo.getPhoneNumber();
                        }
                    }
                    logger.info("-----------------------我是手机号:"+phone);
                    if (appletUserRoleVo != null){ //存在
                        if(appletUserRoleVo.getPhone()!=null && !appletUserRoleVo.getPhone().equals("")){
                            phone=appletUserRoleVo.getPhone();
                        }
                        logger.info("-----------------------我是手机号2222:"+phone);
                        //保存session
                        logger.info("用户存在保存opendid="+appletUserRoleVo.getOpenid());
                        request.getSession().setAttribute("openid",appletUserRoleVo.getOpenid());
                        request.getSession().setAttribute("userid",appletUserRoleVo.getUserID());
                        //将用户信息修改
                        logger.info("-----------------------nickName:"+nickName);
                        if (nickName != null && !nickName.equals("")){ //用户昵称是否存在
                            Users users = new Users();
                            users.setParentID(parentID);
                            users.setMemberId(memberId);
                            users.setNickName(nickName);
                            users.setAvatarUrl(avatarUrl);
                            users.setSex(gender);
                            users.setCity(city);
                            users.setProvince(province);
                            users.setCountry(country);
                            users.setLanguage(language);
                            users.setUserID(appletUserRoleVo.getUserID());
                            users.setPhone(phone);
                            userService.updateById(users);
                            logger.info("-----------------------updateById:1111");
                        }else {
                            Users users = new Users();
                            users.setParentID(parentID);
                            users.setMemberId(memberId);
                            users.setUserID(appletUserRoleVo.getUserID());
                            users.setPhone(phone);
                            userService.updateById(users);
                            logger.info("-----------------------updateById:2222");
                        }
                        AppletUserRoleVo appletUserRoleVo1 = userRolesService.getAppletUserRoleVo(usersQueryWrapper);
                        logger.info("-----------------------我是用户数据:"+appletUserRoleVo1);
                        returnVO.setData(appletUserRoleVo1);
                    }else { // 不存在 创建一条非会员记录
                        Users users = new Users();
                        users.setTypes(0);
                        users.setMemberId(memberId);
                        users.setNickName(nickName);
                        users.setAvatarUrl(avatarUrl);
                        users.setSex(gender);
                        users.setCity(city);
                        users.setProvince(province);
                        users.setCountry(country);
                        users.setLanguage(language);
                        users.setActivity(1);
                        users.setUserName(getCode());
                        users.setCreateDateTime(new Date());
                        users.setAmount(0.0);
                        users.setParentID(parentID); // 归属上级
                        users.setUserType(6);
                        users.setOpenId(openid);
                        users.setCode(getCode());
                        users.setPromotionCode(getCode());
                        users.setPhone(phone);
                        if (userService.save(users)){
                            UserRoles userRoles = new UserRoles();
                            userRoles.setRoleID(6);
                            userRoles.setUserID(users.getUserID());
                            if (userRolesService.save(userRoles)){
                                AppletUserRoleVo appletUserRoleVo1 = userRolesService.getAppletUserRoleVo(usersQueryWrapper);
                                returnVO.setData(appletUserRoleVo1);
                                //保存session
                                logger.info("用户不存在保存opendid="+appletUserRoleVo1.getOpenid());
                                request.getSession().setAttribute("openid",appletUserRoleVo1.getOpenid());
                                request.getSession().setAttribute("userid",appletUserRoleVo1.getUserID());
                            }
                        }
                    }
                }catch (Exception e){
                    logger.error(e.getMessage());
                    return new ReturnVO(ReturnCode.FAIL);
                }
            }
            return returnVO;
        } catch (WxErrorException e) {
            logger.error("微信获取openid异常："+e.getMessage());
            //this.logger.error(e.getMessage(), e);
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    public String getCode(){
        long random1 = System.currentTimeMillis();
        Random random2 = new Random();
        int rd = random2.nextInt(9);
        String dateKey =  random1 + "" + rd;
        return dateKey;
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public String info(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(phoneNoInfo);
    }

    @RequestMapping("/getQRCode")
    public void getQRCode(String openId,HttpServletRequest req,HttpServletResponse res) throws WxErrorException {
        if(StringUtils.isEmpty(openId)){
            if (req.getSession().getAttribute("openid") != null){
                openId = req.getSession().getAttribute("openid").toString();
            }
        }
        if(StringUtils.isEmpty(openId)){
            return;
        }
        final WxMaService wxService = WxMaConfiguration.getMaService(WebConfig.APPID);
        QueryWrapper<Users> recordWrap = new QueryWrapper();
        recordWrap.eq("openId",openId);
        Users user = userService.getOne(recordWrap);
        if(user == null || StringUtils.isEmpty(user.getPromotionCode())){
            return;
        }
        InputStream inputStream = null;
        try {
            WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
            byte[] result = wxService.getQrcodeService().createWxaCodeUnlimitBytes(user.getPromotionCode(),"pages/index/main",430,true,lineColor,false);
            inputStream = new ByteArrayInputStream(result);
            IOUtils.copy(inputStream, res.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
